<?php

namespace app\teacher\controller\say;

use app\common\controller\Frontend;
use app\common\enums\CourseFullTypeEnum;
use app\common\enums\say\SayCategoryTypeEnum;
use app\common\model\banxi\say\SayCategory as SayCategoryModel;
use app\common\model\banxi\say\SayGrade;

class SayCategory extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function listCategory()
    {
        $param = $this->request->param(['index', 'limit', "query", 'studentId', 'courseFullType']);
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $sayCategoryModel = new SayCategoryModel();
        $studentId = $param['studentId'] ?? '';
        //体验课只显示体验课
        $courseFullType = $param['courseFullType'] ?? '';
        if ($courseFullType && $courseFullType == CourseFullTypeEnum::EXPERIENCE) {
            $where[] = ['type', '>', SayCategoryTypeEnum::E1];
        }

        // 预先过滤数据
        $excludeCategoryIds = [];
        if ($studentId) {
            // 查询所有可能需要过滤的分类
            $potentialCategories = $sayCategoryModel->where($where)
                ->where('type', SayCategoryTypeEnum::E1)
                ->column('id');

            foreach ($potentialCategories as $categoryId) {
                $tenchCount = SayGrade::alias('a')->where(['sayCateGoryId' => $categoryId])
                    ->whereExists(function ($query) use ($studentId) {
                        $query->name('banxi_say_teach_sentence')
                            ->alias('b')
                            ->whereColumn('a.id', 'gradeId')
                            ->where('del', 0)
                            ->whereExists(function ($query) use ($studentId) {
                                $query->name('banxi_student_course')
                                    ->whereColumn('b.id', 'courseId')
                                    ->where([
                                        'studentId' => $studentId,
                                        'del' => 0
                                    ]);
                            });
                    })->count();
                if ($tenchCount <= 0) {
                    $excludeCategoryIds[] = $categoryId;
                }
            }
        }

        // 排除没有数据的分类
        if (!empty($excludeCategoryIds)) {
            $where[] = ['id', 'not in', $excludeCategoryIds];
        }

        $list = $sayCategoryModel->where($where)->order([
            'sortNum' => 'desc'
        ])->paginate([
            'page' => $pageParams['page'],
            'list_rows' => $pageParams['limit']
        ]);

        $this->ok('ok', result_row($list));
    }

}